package client

import (
	"context"
	"google.golang.org/grpc"
	"longmen/server/pkg/common/app/etcd"
	"time"
)

type Option func(*clientOption)

type clientOption struct {
	endpoint  string
	timeout   time.Duration
	discovery *etcd.Registry
	opts      []grpc.DialOption
}

func Endpoint(name string) Option {
	return func(cli *clientOption) {
		cli.endpoint = name
	}
}

func Timeout(timeout time.Duration) Option {
	return func(cli *clientOption) {
		cli.timeout = timeout
	}
}

func Discovery(registry *etcd.Registry) Option {
	return func(cli *clientOption) {
		cli.discovery = registry
	}
}

func DialOption(dialOption ...grpc.DialOption) Option {
	return func(o *clientOption) {
		o.opts = append(o.opts, dialOption...)
	}
}

func New(opts ...Option) *clientOption {
	cli := &clientOption{}
	for _, o := range opts {
		o(cli)
	}
	return cli
}

func (c *clientOption) Dial(ctx context.Context) (*grpc.ClientConn, error) {
	grpcOpts := []grpc.DialOption{
		grpc.WithInsecure(),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
	}
	if len(c.opts) != 0 {
		grpcOpts = append(grpcOpts, c.opts...)
	}
	if c.discovery != nil {
		grpcOpts = append(grpcOpts, grpc.WithResolvers(
			NewBuilder(c.discovery),
		))
	}
	return grpc.DialContext(ctx, c.endpoint, grpcOpts...)
}
